package advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class LogAdvice {

    @Pointcut(value = "execution(* service.impl.*.*(..))")
    public void pointCutName(){}
    @Before("pointCutName()")
    public void before(JoinPoint jp){
        Object target = jp.getTarget();
        Signature signature = jp.getSignature();
        Object[] args = jp.getArgs();
        System.out.println("在"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"执行了"+signature.getName()+"方法，参数为"+ Arrays.toString(args));
    }

    @AfterReturning(value="pointCutName()",returning = "resultValue")
    public void afterReturn(JoinPoint jp, Object resultValue){
        Object target = jp.getThis();
        Signature signature = jp.getSignature();
        Object[] args = jp.getArgs();
        System.out.println("在"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"执行了"+signature.getName()+"方法，方法返回值为"+ resultValue);
    }

    @AfterThrowing(value = "pointCutName()",throwing = "e")
    public void afterThrowing(JoinPoint jp,Exception e){
        Object target = jp.getThis();
        Signature signature = jp.getSignature();
        Object[] args = jp.getArgs();
        System.out.println("在"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"执行了"+signature.getName()+"方法，出现异常为"+ e.getMessage());

    }

    @After("pointCutName()")
    public void after(JoinPoint jp){
        Object target = jp.getThis();
        Signature signature = jp.getSignature();
        Object[] args = jp.getArgs();
        System.out.println("在"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"执行了"+signature.getName()+"方法，参数为"+ Arrays.toString(args));

    }

    @Around("pointCutName()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
    {
        Object result=null;
        try {
            System.out.println("环绕通知—前置通知");
            result = proceedingJoinPoint.proceed();
            System.out.println("环绕通知—后置正常返回通知");
        } catch (Throwable throwable) {
            System.out.println("环绕通知—异常通知");
        } finally {
            System.out.println("环绕通知—后置通知");
        }
        return result;
    }
}
